/*
 * Copyright (c) 2025 CAX Conversion Project
 */
package com.comac.ins.isfd.service.impl;


import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.comac.ins.common.core.exception.base.BaseException;
import com.comac.ins.common.core.utils.MapstructUtils;
import com.comac.ins.common.excel.utils.ExcelUtil;
import com.comac.ins.common.mybatis.core.page.PageQuery;
import com.comac.ins.common.mybatis.core.page.TableDataInfo;
import com.comac.ins.isfd.constant.enums.IsfdMetadataTableNameEnum;
import com.comac.ins.isfd.domain.IsfdCompositeMaterial;
import com.comac.ins.isfd.domain.bo.IsfdCompositeMaterialBo;
import com.comac.ins.isfd.domain.bo.IsfdLayupMetalCaseMetaBo;
import com.comac.ins.isfd.domain.bo.query.IsfdCompositeMaterialQueryBo;
import com.comac.ins.isfd.domain.vo.IsfdCompositeMaterialVo;
import com.comac.ins.isfd.domain.vo.IsfdLayupMetalCaseMetaVo;
import com.comac.ins.isfd.mapper.IsfdCompositeMaterialMapper;
import com.comac.ins.isfd.service.IIsfdCompositeMaterialService;
import com.comac.ins.isfd.service.IIsfdMetadataImportService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * 【请填写功能名称】Service业务层处理
 *
 * @author Lion Li
 * @date 2024-08-02
 */
@RequiredArgsConstructor
@Service
@Slf4j
public class IsfdCompositeMaterialServiceImpl implements IIsfdCompositeMaterialService, IIsfdMetadataImportService {

    private final IsfdCompositeMaterialMapper baseMapper;

    /**
     * 查询【请填写功能名称】
     *
     * @param id 主键
     * @return 【请填写功能名称】
     */
    @Override
    public IsfdCompositeMaterialVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询【请填写功能名称】列表
     *
     * @param bo        查询条件
     * @return 【请填写功能名称】分页列表
     */
    @Override
    public TableDataInfo<IsfdCompositeMaterialVo> queryPageList(IsfdCompositeMaterialQueryBo bo) {
        PageQuery pageQuery = new PageQuery();
        pageQuery.setPageNum(bo.getPageNum());
        pageQuery.setPageSize(bo.getPageSize());
        LambdaQueryWrapper<IsfdCompositeMaterial> lqw = buildQueryWrapper(bo);
        Page<IsfdCompositeMaterialVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的【请填写功能名称】列表
     *
     * @param bo 查询条件
     * @return 【请填写功能名称】列表
     */
    @Override
    public List<IsfdCompositeMaterialVo> queryList(IsfdCompositeMaterialQueryBo bo) {
        LambdaQueryWrapper<IsfdCompositeMaterial> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<IsfdCompositeMaterial> buildQueryWrapper(IsfdCompositeMaterialQueryBo bo) {
        LambdaQueryWrapper<IsfdCompositeMaterial> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(bo.getMaterialName()), IsfdCompositeMaterial::getMaterialName, bo.getMaterialName());
        lqw.eq(StringUtils.isNotBlank(bo.getMaterialNumber()), IsfdCompositeMaterial::getMaterialNumber, bo.getMaterialNumber());
        lqw.eq(bo.getE1() != null, IsfdCompositeMaterial::getE1, bo.getE1());
        lqw.eq(bo.getE2() != null, IsfdCompositeMaterial::getE2, bo.getE2());
        lqw.eq(bo.getNu12() != null, IsfdCompositeMaterial::getNu12, bo.getNu12());
        lqw.eq(bo.getG12() != null, IsfdCompositeMaterial::getG12, bo.getG12());
        lqw.eq(bo.getG1z() != null, IsfdCompositeMaterial::getG1z, bo.getG1z());
        lqw.eq(bo.getG2z() != null, IsfdCompositeMaterial::getG2z, bo.getG2z());
        lqw.eq(bo.getRho() != null, IsfdCompositeMaterial::getRho, bo.getRho());
        lqw.eq(bo.getLongitudinalCteValue() != null, IsfdCompositeMaterial::getLongitudinalCteValue, bo.getLongitudinalCteValue());
        lqw.eq(bo.getTransverseCteValue() != null, IsfdCompositeMaterial::getTransverseCteValue, bo.getTransverseCteValue());
        lqw.in(CollectionUtil.isNotEmpty(bo.getMetadataManagementIds()), IsfdCompositeMaterial::getMetadataManagementId, bo.getMetadataManagementIds());
        return lqw;
    }

    /**
     * 新增【请填写功能名称】
     *
     * @param bo 【请填写功能名称】
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(IsfdCompositeMaterialBo bo) {
        IsfdCompositeMaterial add = MapstructUtils.convert(bo, IsfdCompositeMaterial.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改【请填写功能名称】
     *
     * @param bo 【请填写功能名称】
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(IsfdCompositeMaterialBo bo) {
        IsfdCompositeMaterial update = MapstructUtils.convert(bo, IsfdCompositeMaterial.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(IsfdCompositeMaterial entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除【请填写功能名称】信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public String selectByTableName() {
        return IsfdMetadataTableNameEnum.ISFD_COMPOSITE_MATERIAL.getValue();
    }

    @Override
    public Long excelImport(File excelImportFile, String metadataManagementId) {
        long successCount = 0L;
        try (InputStream is = new FileInputStream(excelImportFile)) {
            List<IsfdCompositeMaterialVo> targetVo = ExcelUtil.importExcel(is, IsfdCompositeMaterialVo.class);
            for (IsfdCompositeMaterialVo vo : targetVo) {
                IsfdCompositeMaterialBo bo = MapstructUtils.convert(vo, IsfdCompositeMaterialBo.class);

                try{
                    bo.setMetadataManagementId(metadataManagementId);
                    insertByBo(bo);
                    successCount++;
                } catch (Exception e) {
                    log.error("复合材料数据导入失败", e);
                }
            }

        } catch (Exception e) {
            log.error("sheet文件转换为实体类失败", e);
            throw new BaseException("sheet文件转换为实体类失败");
        }

        return successCount;
    }
}
